import ctypes
import numpy
import netCDF4
import os
import sys
from copy import copy as copy_copy

# --------------------------------------------------------------------
# Aliases for ctypes
# --------------------------------------------------------------------
_sizeof_buffer = 257
_string_buffer = ctypes.create_string_buffer(_sizeof_buffer)
_c_char_p      = ctypes.c_char_p
_c_int         = ctypes.c_int
_c_float       = ctypes.c_float
_c_double      = ctypes.c_double
_c_size_t      = ctypes.c_size_t
_pointer       = ctypes.pointer
_POINTER       = ctypes.POINTER

_ctypes_POINTER = {4: _POINTER(_c_float),
                   8: _POINTER(_c_double)}

# --------------------------------------------------------------------
# Load the Udunits-2 library and read the database
# --------------------------------------------------------------------
if sys.platform == 'darwin':
    # This has been tested on Mac OSX 10.5.8 and 10.6.8
    _udunits = ctypes.CDLL('libudunits2.0.dylib')
else:
    # Linux
    _udunits = ctypes.CDLL('libudunits2.so.0')

# Get the name of the XML-formatted unit-database
_unit_database = os.path.join(os.path.dirname(__file__),
                              'etc/udunits/udunits2.xml')

if os.path.isfile(_unit_database):
    # The database included with this module exists, so use it
    _unit_database = _c_char_p(_unit_database)
else:
    # Use the default (non-CF) database
    print 'WARNING: Using the default (non-CF) Udunits database'
    _unit_database = None
#--- End: if

# Suppress "overrides prefixed-unit" messages. This also suppresses
# all other error messages - so watch out!
#
# Messages may be turned back on by calling the module function
# udunits_error_messages.
_ut_set_error_message_handler = _udunits.ut_set_error_message_handler
_ut_set_error_message_handler(_udunits.ut_ignore)

# Read the data base
#print 'units: before _udunits.ut_read_xml(',_unit_database,')'
_ut_system = _udunits.ut_read_xml(_unit_database)
#print 'units: after  _udunits.ut_read_xml(',_unit_database,')'

# Reinstate the reporting of error messages
#_ut_set_error_message_handler(_udunits.ut_write_to_stderr)

# --------------------------------------------------------------------
# Aliases for the UDUNITS-2 C API. See
#     www.unidata.ucar.edu/software/udunits/udunits-2/udunits2lib.html
# for documentation.
# --------------------------------------------------------------------
_ut_format          = _udunits.ut_format
_ut_trim            = _udunits.ut_trim
_ut_parse           = _udunits.ut_parse
_ut_compare         = _udunits.ut_compare
_ut_are_convertible = _udunits.ut_are_convertible
_ut_get_converter   = _udunits.ut_get_converter
_ut_divide          = _udunits.ut_divide
_ut_offset          = _udunits.ut_offset
_ut_raise           = _udunits.ut_raise
_ut_scale           = _udunits.ut_scale
_ut_multiply        = _udunits.ut_multiply
_ut_log             = _udunits.ut_log
_ut_root            = _udunits.ut_root
_ut_free            = _udunits.ut_free
_cv_convert_floats  = _udunits.cv_convert_floats
_cv_convert_doubles = _udunits.cv_convert_doubles
_cv_convert_double  = _udunits.cv_convert_double
_cv_free            = _udunits.cv_free

_UT_ASCII      = 0
_UT_NAMES      = 4
_UT_DEFINITION = 8

_cv_convert_array = {4: _cv_convert_floats,
                     8: _cv_convert_doubles}

# --------------------------------------------------------------------
# Aliases for netCDF4.netcdftime classes
# --------------------------------------------------------------------
_utime    = netCDF4.netcdftime.utime
_datetime = netCDF4.netcdftime.datetime

# --------------------------------------------------------------------
# Aliases for netCDF4.netcdftime functions
# --------------------------------------------------------------------
_num2date = netCDF4.netcdftime.num2date
_date2num = netCDF4.netcdftime.date2num

# --------------------------------------------------------------------
# Save some useful units
# --------------------------------------------------------------------
# A time ut_unit. Not that if the '_jd0' attribute of the
# netCDF4.netcdftime.utime object ever changes from Julian days, then
# _time_ut_unit will have to change accordingly.
_time_ut_unit = _ut_parse(_ut_system, _c_char_p('day'), _UT_ASCII)

# A pressure ut_unit
_pressure_ut_unit = _ut_parse(_ut_system, _c_char_p('pascal'), _UT_ASCII)

# --------------------------------------------------------------------
# Set the default calendar type according to the CF conventions
# --------------------------------------------------------------------
_default_calendar = 'gregorian'

# --------------------------------------------------------------------
# Set month lengths in days for non-leap years (_days_in_month[0,1:])
# and leap years (_days_in_month[1,1:])
# --------------------------------------------------------------------
_days_in_month = numpy.array([[-9999, 31, 28, 31, 30, 31, 30, 31, 31,
                                30, 31, 30, 31],
                              [-9999, 31, 29, 31, 30, 31, 30, 31, 31,
                                30, 31, 30, 31]])

# --------------------------------------------------------------------
# Function to control Udunits error messages
# --------------------------------------------------------------------
def udunits_error_messages(flag):
    '''

Control the printing of error messages from Udunits, which are turned
off by default.

:Parameters:

    flag : bool
        Set to True to print Udunits error messages and False to not
        print Udunits error messages.

:Returns:

    None

**Examples**

>>> udunits_error_messages(True)
>>> udunits_error_messages(False)

'''
    if flag:
        _ut_set_error_message_handler(_udunits.ut_write_to_stderr)
    else:
        _ut_set_error_message_handler(_udunits.ut_ignore)
#--- End: def


def _month_length(year, month, calendar, _days_in_month=_days_in_month):
    '''

Find month lengths in days for each year/month pairing in the input
numpy arrays 'year' and 'month', both of which must have the same
shape. 'calendar' must be one of the standard CF calendar types.

:Parameters:


'''
    shape = month.shape
    if calendar in ('standard', 'gregorian'):
        leap = numpy.where(year % 4 == 0, 1, 0)
        leap = numpy.where((year > 1582) &
                           (year % 100 == 0) & (year % 400 != 0),
                           0, leap)
    elif calendar == '360_day':
        days_in_month = numpy.empty(shape)
        days_in_month.fill(30)
        return days_in_month

    elif calendar in ('all_leap', '366_day'):
        leap = numpy.zeros(shape)

    elif calendar in ('no_leap', '365_day'):
        leap = numpy.ones(shape)

    elif calendar == 'proleptic_gregorian':
        leap = numpy.where(year % 4 == 0, 1, 0)
        leap = numpy.where((year % 100 == 0) & (year % 400 != 0),
                           0, leap)

    days_in_month = numpy.array([_days_in_month[l, m]
                                 for l, m in zip(leap.flat, month.flat)])
    days_in_month.resize(shape)

    return days_in_month
#--- End: def

def _proper_date(year, month, day, calendar, fix=False,
                 _days_in_month=_days_in_month):
    '''

Given equally shaped numpy arrays of 'year', 'month', 'day' adjust
them *in place* to be proper dates. 'calendar' must be one of the
standard CF calendar types.

Excessive number of months are converted to years but excessive days
are not converted to months nor years. If a day is illegal in the
proper date then a ValueError is raised, unless 'fix' is True, in
which case the day is lowered to the nearest legal date:

    2000/26/1 -> 2002/3/1

    2001/2/31 -> ValueError if 'fix' is False
    2001/2/31 -> 2001/2/28  if 'fix' is True
    2001/2/99 -> 2001/2/28  if 'fix' is True

:Parameters:

'''
#    y, month = divmod(month, 12)
#    year += y

    year      += month // 12
    month[...] = month % 12

    mask       = (month == 0)
    year[...]  = numpy.where(mask, year-1, year)
    month[...] = numpy.where(mask, 12, month)
    del mask

    days_in_month = _month_length(year, month, calendar,
                                  _days_in_month=_days_in_month)

    if fix:
        day[...] = numpy.where(day > days_in_month, days_in_month, day)
    elif (day > days_in_month).any():
        raise ValueError("Illegal date(s) in %s calendar" % calendar)

    return year, month, day
#--- End: def

#def _change_calendar(from_units, to_units, fix=False, inplace=False,
#                     _days_in_month=_days_in_month):
#    '''
#
#Give a new calendar to Time object, possibly adjusting dates which are
#illegal in the new calendar.
#
#:argument calendar: The calendar to change to. May take one of two forms:
#
#                    1. A CF compliant 'calendar' attribute giving the
#                       new calendar, such as 'gregorian'.
#
#                    2. A Time object, from which the new calendar is
#                       taken.
#
#:type calendar: `str` or `Time`
#
#    fix: If False then raise an exception when encountering
#                dates which are illegal in the new calendar, such as
#                2001-02-30 in the gregorian calendar.
#
#                If True then replace dates which are illegal in the
#                new calendar with the closest earlier legal date. For
#                example 2001-02-30 in gregorian calendar would be
#                replaced with 2000-02-28.
#
#:type fix: `bool`
#
#:returns: A Time instance
#
#*Examples*
#
#>>> t = Time([1,2,3], units='days since 2000-02-27', calendar='gregorian')
#>>> u = t.change_calendar('360_day')
#>>> print t
#[2000-02-28 00:00:00 2000-02-29 00:00:00 2000-03-01 00:00:00]
#>>> print u
#[2000-02-28 00:00:00 2000-02-29 00:00:00 2000-03-01 00:00:00]
#
#>>> t = Time([1,2,3], units='days since 2000-02-27', calendar='360_day')
#>>> u = t.change_calendar('gregorian', fix=True)
#>>> print(t)
#[2000-02-28 00:00:00 2000-02-29 00:00:00 2000-02-30 00:00:00]
#>>> print u
#[2000-02-28 00:00:00 2000-02-29 00:00:00 2000-02-29 00:00:00]
#
#>>> u = t.change_calendar('gregorian')
#ValueError: Can't convert calendar: Illegal date(s) in gregorian calendar
#
#'''
#    datetime = _num2date(x,
#                         from_units._rtime.unit_string,
#                         calendar=from_units._rtime.calendar)
#
#    shape = None
#    if isinstance(datetime, numpy.ndarray):
#        shape  = x.shape
#        year   = numpy.array([dt.year   for dt in datetime.flat])
#        month  = numpy.array([dt.month  for dt in datetime.flat])
#        day    = numpy.array([dt.day    for dt in datetime.flat])
#        hour   = numpy.array([dt.hour   for dt in datetime.flat]).flat
#        minute = numpy.array([dt.minute for dt in datetime.flat]).flat
#        second = numpy.array([dt.second for dt in datetime.flat]).flat
#    else:
#        year   = numpy.array(datetime.year)
#        month  = numpy.array(datetime.month)
#        day    = numpy.array(datetime.day)
#        hour   = datetime.hour
#        minute = datetime.minute
#        second = datetime.second
#    #--- End: if
#
#    year, month, day = _proper_date(year, month, day,
#                                    to_units._rtime.calendar,
#                                    fix=fix,
#                                    _days_in_month=_days_in_month)
#    # Note that i) _proper_date returns three numpy arrays and ii)
#    # _proper_date will raise a ValueError if fix=False and illegal
#    # dates are produced.
#
#    datetime = numpy.array([_datetime(Y,M,D,h,m,s)
#                            for Y,M,D,h,m,s in zip(year.flat,
#                                                   month.flat,
#                                                   day.flat,
#                                                   hour,
#                                                   minute,
#                                                   second)])
#
#    # Try to return a scalar number
#    if shape is None:
#        return _date2num(datetime.item())
#
#    # Still here? Then return an array of numbers (after reshaping
#    # datetime to be the same shape as the input array)
#    datetime.resize(shape)
#    if inplace:
#        # Convert integer array into a float array in place
#        if x.dtype.kind is 'i':
#            if x.dtype.char is 'i':
#                y      = x.view(dtype='float32')
#                y[...] = x
#                x.dtype = numpy.dtype('float32')
#            elif x.dtype.char is 'l':
#                y      = x.view(dtype='float64')
#                y[...] = x
#                x.dtype = numpy.dtype('float64')
#        #--- End: if
#        x[...] = _date2num(datetime)
#    else:
#        return _date2num(datetime)
##--- End: def

# --------------------------------------------------------------------
# The Units class
# --------------------------------------------------------------------
class Units(object):
    '''

Store, combine and compare physical units and convert numeric values
to different units.

Units are as defined in UNIDATA's Udunits-2 package, with a few
exceptions for greater consistency with the CF conventions namely
support for CF calendars and new units definitions.


**Modifications to the standard Udunits database**

Whilst a standard Udunits-2 database may be used, greater consistency
with CF is achieved by using a modified database. The following units
are either new to, modified from, or removed from the standard
Udunits-2 database (version 2.1.24):

=======================  ======  ============  ==============
Unit name                Symbol  Definition    Status
=======================  ======  ============  ==============
practical_salinity_unit  psu     1e-3          New unit
level                            1             New unit
sigma_level                      1             New unit
layer                            1             New unit
decibel                  dB      1             New unit
bel                              10 dB         New unit
sverdrup                 Sv      1e6 m3 s-1    Added symbol
sievert                          J kg-1        Removed symbol
=======================  ======  ============  ==============

Plural forms of the new units' names are allowed, such as
``practical_salinity_units``.

The modified database is in the *udunits* subdirectory of the *etc*
directory found in the same location as this module.


**Accessing units**

Units may be set, retrieved and deleted via the `units` attribute. Its
value is a string that can be recognized by UNIDATA's Udunits-2
package, with the few exceptions given in the CF conventions.

>>> u = Units('m s-1')
>>> u
<Cf Units: 'm s-1'>
>>> u.units = 'days since 2004-3-1'
>>> u
<CF Units: days since 2004-3-1>


**Equality and equivalence of units**

There are methods for assessing whether two units are equivalent or
equal. Two units are equivalent if numeric values in one unit are
convertible to numeric values in the other unit (such as
``kilometres`` and ``metres``). Two units are equal if they are
equivalent and their conversion is a scale factor of 1 and an offset
of 0 (such as ``kilometres`` and ``1000 metres``). Note that
equivalence and equality are based on internally stored binary
representations of the units, rather than their string
representations.

>>> u = Units('m/s')
>>> v = Units('m s-1')
>>> w = Units('km.s-1')
>>> x = Units('0.001 kilometer.second-1')
>>> y = Units('gram')

>>> u.equivalent(v), u.equals(v),  u == v
(True, True, True)
>>> u.equivalent(w), u.equals(w)
(True, False)
>>> u.equivalent(x), u.equals(x)
(True, True)
>>> u.equivalent(y), u.equals(y)
(False, False)


**Time and reference time units**

Time units may be given as durations of time (*time units*) or as an
amount of time since a reference time (*reference time units*):

>>> v = Units()
>>> v.units = 's'
>>> v.units = 'day'
>>> v.units = 'days since 1970-01-01'
>>> v.units = 'seconds since 1992-10-8 15:15:42.5 -6:00'

.. note::

   It is recommended that the units ``year`` and ``month`` be used
   with caution, as explained in the following excerpt from the CF
   conventions: "The Udunits package defines a year to be exactly
   365.242198781 days (the interval between 2 successive passages of
   the sun through vernal equinox). It is not a calendar year. Udunits
   includes the following definitions for years: a common_year is 365
   days, a leap_year is 366 days, a Julian_year is 365.25 days, and a
   Gregorian_year is 365.2425 days. For similar reasons the unit
   ``month``, which is defined to be exactly year/12, should also be
   used with caution."

**Calendar**

The date given in reference time units is associated with one of the
calendars recognized by the CF conventions and may be set with the
`calendar` attribute. However, as in the CF conventions, if the
calendar is not set then, for the purposes of calculation and
comparison, it defaults to the mixed Gregorian/Julian calendar as
defined by Udunits:

>>> u = Units('days since 2000-1-1')
>>> u.calendar
AttributeError: Can't get 'Units' attribute 'calendar'
>>> v = Units('days since 2000-1-1')
>>> v.calendar = 'gregorian'
>>> v.equals(u)
True


**Arithmetic with units**

The following operators, operations and assignments are overloaded:

Comparison operators:

    ``==, !=``

Binary arithmetic operations:

    ``+, -, *, /, pow(), **``

Unary arithmetic operations:

    ``-, +``

Augmented arithmetic assignments:

    ``+=, -=, *=, /=, **=``

The comparison operations return a boolean and all other operations
return a new units object or modify the units object in place.

>>> u = Units('m')
<CF Units: m>

>>> v = u * 1000
>>> v
<CF Units: 1000 m>

>>> u == v
False
>>> u != v
True

>>> u **= 2
>>> u
<CF Units: m2>


It is also possible to create the logarithm of a unit corresponding to
the given logarithmic base:

>>> u = Units('seconds')
>>> u.log(10)
<CF Units: lg(re 1 s)>


**Modifying data for equivalent units**

Any numpy array or python numeric type may be modified for equivalent
units using the `conform` static method.

>>> Units.conform(2, Units('km'), Units('m'))
2000.0

>>> import numpy
>>> a = numpy.arange(5.0)
>>> Units.conform(a, Units('minute'), Units('second'))
array([   0.,   60.,  120.,  180.,  240.])
>>> a
array([ 0.,  1.,  2.,  3.,  4.])

If the *inplace* keyword is True, then a numpy array is modified in
place, without any copying overheads:

>>> Units.conform(a,
                  Units('days since 2000-12-1'),
                  Units('days since 2001-1-1'), inplace=True)
array([-31., -30., -29., -28., -27.])
>>> a
array([-31., -30., -29., -28., -27.])

'''
    __slots__ = ['_ut_unit',
                 '_units',
                 '_calendar',
                 '_rtime',
                 ]

    def __init__(self,
                 units=None, calendar=None,
                 format=None, names=None, definition=None,
                 _ut_unit=None):
        '''

**Initialization**

:Parameters:

    units : str, optional
        Set the new units from this string.

    calendar : str, optional
        Set the calendar for reference time units.

    format : bool, optional
        Format the string representation of the units in a
        standardized manner. See the `format` method.

    names : bool, optional
        Format the string representation of the units using names
        instead of symbols. See the `format` method.

    definition : bool, optional
        Format the string representation of the units using basic
        units. See the `format` method.

    _ut_unit : int, optional
        Set the new units from this Udunits binary unit
        representation. This should be an integer returned by a call
        to `ut_parse` function of Udunits. Ignored if `units` is set.

'''
        # Do calendar before units to prevent the possibility of
        # calculating _rtime twice
        if calendar is not None:
            self.calendar = calendar

        if units is not None:
            self.units = units
            if format or names is not None or definition is not None:
                self.units = self.format(names=names, definition=definition)

        elif _ut_unit is not None:
            self._ut_unit = _ut_unit
            self.units = self.format(names=names, definition=definition)
    #--- End: def

    def __hash__(self):
        '''
x.__hash__() <==> hash(x)

'''
        if not self:
            return hash(self.__class__)

        if not self.isreftime:
            return hash(self._ut_unit)

        return hash((self._ut_unit, self._rtime._jd0, self._rtime.calendar,
                     self._rtime.tzoffset))
    #--- End: def

    def __repr__(self):
        '''
x.__repr__() <==> repr(x)

'''
        if hasattr(self, 'units'):
            return '<CF %s: %s>' % (self.__class__.__name__, repr(str(self)))

        return '<CF %s: >' % self.__class__.__name__        
    #--- End: def

    def __str__(self):
        '''
x.__str__() <==> str(x)

'''
        string = []
        if hasattr(self, 'units'):
            string.append(self.units)
        if hasattr(self, 'calendar'):
            string.append('calendar=%s' % self.calendar)
        return ' '.join(string)
    #--- End: def

    def __deepcopy__(self, memo):
        '''

Used if copy.deepcopy is called on the variable.

'''
        return self.copy()
    #--- End: def

    def __nonzero__(self):
        '''
x.__nonzero__() <==> x!=0

'''
        return hasattr(self, '_ut_unit')
    #--- End: def

    def __eq__(self, other):
        '''
x.__eq__(y) <==> x==y

'''
        return self.equals(other)
    #--- End: def

    def __ne__(self, other):
        '''
x.__ne__(y) <==> x!=y

'''
        return not self.equals(other)
    #--- End: def

    def __sub__(self, other):
        '''
x.__sub__(y) <==> x-y

'''
        try:
            if (self.isreftime and
                isinstance(other, self.__class__) and other.isreftime):
                new = type(self)(_ut_unit=self._ut_unit)
            else:
                new = type(self)(_ut_unit=_ut_offset(self._ut_unit,
                                                     _c_double(other)))
                if self.isreftime:
                    # Reference time - number = reference time
                    new = self.change_reftime_units(new.units)
            #--- End: if

        except (TypeError, AttributeError):
            raise ValueError("Can't subtract %s from %s" %
                             (repr(other), repr(self)))

        return new
    #--- End: def

    def __add__(self, other):
        '''
x.__add__(y) <==> x+y

'''
        try:
            return self - (-other)
        except ValueError:
            raise ValueError("Can't add %s to %s" %
                             (repr(other), repr(self)))
    #--- End: def

    def __mul__(self, other):
        '''
x.__mul__(y) <==> x*y

'''
        try:
            if self._rtime.calendar != other._rtime.calendar:
                raise ValueError("Can't multiply %s by %s" %
                                 (repr(self), repr(other)))
        except AttributeError:
            pass

        try:
            return type(self)(_ut_unit=_ut_multiply(self._ut_unit,
                                                    other._ut_unit))
        except TypeError:
            pass
        except AttributeError:
            try:
                new = type(self)(_ut_unit=_ut_scale(_c_double(other),
                                                    self._ut_unit))
                if self.isreftime:
                    # Reference time * number = reference time
                    units    = self.units.split(' since ')
                    units[0] = new.units
                    units    = ' since '.join(units)
                    new      = type(self)(units=units)
                #--- End: if
                return new
            except (AttributeError, TypeError):
                pass
        #--- End: def

        raise ValueError("Can't multiply %s by %s" %
                         (repr(self), repr(other)))
    #--- End: def

    def __div__(self, other):
        '''
x.__div__(y) <==> x/y

'''
        try:
            if self._rtime.calendar != other._rtime.calendar:
                raise ValueError("Can't divide %s by %s" %
                                 (repr(self), repr(other)))
        except AttributeError:
            pass

        try:
            return type(self)(_ut_unit=_ut_divide(self._ut_unit,
                                                  other._ut_unit))
        except TypeError:
            pass
        except AttributeError:
            try:
                new = type(self)(_ut_unit=_ut_scale(_c_double(1.0/other),
                                                    self._ut_unit))
                if self.isreftime:
                    # Reference time / number = reference time
                    units    = self.units.split(' since ')
                    units[0] = new.units
                    units    = ' since '.join(units)
                    new      = type(self)(units=units)
                #--- End: if
                return new
            except (AttributeError, TypeError):
                pass
        #--- End: def

        raise ValueError("Can't divide %s by %s" %
                         (repr(self), repr(other)))
    #--- End: def

    def __pow__(self, other, modulo=None):
        '''
x.__pow__(y) <==> x**y

y must be either an integer or the reciprocal of a positive integer.

'''
        if modulo is not None:
            raise NotImplementedError(
                "3-argument power not supported for '%s'" %
                self.__class__.__name__)

        if hasattr(self, '_ut_unit'):
            ut_unit = self._ut_unit
            try:
                return type(self)(_ut_unit=_ut_raise(ut_unit,
                                                     _c_int(other)))
            except TypeError:
                pass

            # If other is a float and (1/other) is a positive integer
            # then take the (1/other)-th root. E.g. if other is 0.125
            # then we take the 8-th root.
            if isinstance(other, float) and 0 < other <= 1:
                recip_other = 1/other
                root        = int(recip_other)
                if recip_other == root:
                    ut_unit = _ut_root(ut_unit, _c_int(root))
                    if ut_unit:
                        return type(self)(_ut_unit=ut_unit)
            #--- End: if
        #--- End: if

        raise ValueError("Can't raise %s to the power %s" %
                         (repr(self), repr(other)))
    #--- End: def

    def __isub__(self, other):
        '''
x.__isub__(y) <==> x-=y

'''
        self = self.__sub__(other)
        return self
    #--- End def

    def __iadd__(self, other):
        '''
x.__iadd__(y) <==> x+=y

'''
#        if hasattr(self, '_ut_unit'):
#            old_ut_unit = self._ut_unit
        self = self.__add__(other)
        return self
    #--- End def

    def __imul__(self, other):
        '''
x.__imul__(y) <==> x*=y

'''
#        if hasattr(self, '_ut_unit'):
#            old_ut_unit = self._ut_unit
        self = self.__mul__(other)
        return self
    #--- End def

    def __idiv__(self, other):
        '''
x.__idiv__(y) <==> x/=y

'''
        self = self.__div__(other)
        return self
    #--- End def

    def __ipow__(self, other):
        '''
x.__ipow__(y) <==> x**=y

'''
        self = self.__pow__(other)
        return self
    #--- End def

    def __rsub__(self, other):
        '''
x.__rsub__(y) <==> y-x

'''
        return self.__mul__(-1) + other
    #--- End def

    def __radd__(self, other):
        '''
x.__radd__(y) <==> y+x

'''
        return self.__add__(other)
    #--- End def

    def __rmul__(self, other):
        '''
x.__rmul__(y) <==> y*x

'''
        return self.__mul__(other)
    #--- End def

    def __rdiv__(self, other):
        '''
x.__rdiv__(y) <==> y/x

'''
        return self.__pow__(-1) * other
    #--- End def

    def __neg__(self):
        '''
x.__neg__() <==> -x

'''
        return self * -1
    #--- End def

    def __pos__(self):
        '''
x.__pos__() <==> +x

'''
        return self.copy()
    #--- End def

    # ----------------------------------------------------------------
    # Attribute: ispressure
    # ----------------------------------------------------------------
    @property
    def ispressure(self):
        '''

True if the units are pressure units, false otherwise.

**Examples**

>>> u = Units(units='bar')
>>> u.ispressure
True

>>> u = Units(units='hours since 2100-1-1', calendar='noleap')
>>> u.ispressure
False

'''
        if hasattr(self, '_ut_unit'):
            return _ut_are_convertible(self._ut_unit, _pressure_ut_unit)

        return False
    #--- End: def

    # ----------------------------------------------------------------
    # Attribute: islatitude
    # ----------------------------------------------------------------
    @property
    def islatitude(self):
        '''

True if the units are latitude units, i.e. if the *units* attribute is
'degrees_north', false otherwise.

**Examples**

>>> u = Units(units='degrees_north')
>>> u.islatitude
True

>>> u = Units(units='degrees')
>>> u.islatitude
False

>>> u = Units(units='degrees_east')
>>> u.islatitude
False

'''
        if hasattr(self, 'units'):
            return self.units == 'degrees_north'

        return False
    #--- End: def

    # ----------------------------------------------------------------
    # Attribute: islongitude
    # ----------------------------------------------------------------
    @property
    def islongitude(self):
        '''

True if the units are longitude units, i.e. if the *units* attribute
is 'degrees_east', false otherwise.

**Examples**

>>> u = Units(units='degrees_east')
>>> u.islongitude
True

>>> u = Units(units='degrees')
>>> u.islongitude
False

>>> u = Units(units='degrees_north')
>>> u.islongitude
False

'''
        if hasattr(self, 'units'):
            return self.units == 'degrees_east'

        return False
    #--- End: def

    # ----------------------------------------------------------------
    # Attribute: istime
    # ----------------------------------------------------------------
    @property
    def istime(self):
        '''

True if the units are time units, False otherwise.

Note that reference time units are not time units.

**Examples**

>>> u = Units(units='days')
>>> u.istime
True

>>> u = Units(units='hours since 2100-1-1', calendar='noleap')
>>> u.istime
False

>>> u = Units(calendar='360_day')
>>> u.istime
False

>>> u = Units(units='kg')
>>> u.istime
False

'''
        if hasattr(self, '_ut_unit'):
            return (not self.isreftime and
                    _ut_are_convertible(self._ut_unit, _time_ut_unit))

        return False
    #--- End: def

    # ----------------------------------------------------------------
    # Attribute: isreftime
    # ----------------------------------------------------------------
    @property
    def isreftime(self):
        '''

True if the units are reference time units, false otherwise.

Note that time units are not reference time units and that the
existence of the `calendar` attribute on its own is not sufficient for
identifying the presence of reference time units.

**Examples**

>>> u = Units(units='days since 1989-1-1')
>>> u.isreftime
True

>>> u = Units(units='hours since 2100-1-1', calendar='noleap')
>>> u.isreftime
True

>>> u = Units(units='kg')
>>> u.isreftime
False

>>> u = Units(units='hours')
>>> u.isreftime
False

>>> u = Units(calendar='360_day')
>>> u.isreftime
False

'''
        return hasattr(self, '_rtime')
    #--- End: def

    # ----------------------------------------------------------------
    # Property attribute: calendar
    # ----------------------------------------------------------------
    @property
    def calendar(self):
        '''
        
The calendar CF attribute for reference time units.

Note that deleting the calendar will adjust the reference time units
for the default CF calendar ('gregorian'), if necessary.

**Examples**

>>> u = Units()
>>> u.calendar = 'gregorian'
>>> u.calendar
'gregorian'

>>> u = Units(calendar='365_day')
>>> u.calendar
'365_day'
>>> del u.calendar

'''
        if hasattr(self, '_calendar'):
            return self._calendar

        raise AttributeError("%s has no attribute 'calendar'" %
                             self.__class__.__name__)
    #--- End: def

    @calendar.setter
    def calendar(self, value):
        # Note that setting the `calendar` attribute may cause the
        # `_rtime` attribute to be recalculated for the new calendar,
        # if necessary.
        if hasattr(self, 'units') and not self.isreftime:
            # Can't set the calendar of non-reference time units
            return

        self._calendar = value
        if (hasattr(self, '_rtime') and self._rtime.calendar != value):
            self.units = self._units
    #--- End: def

    @calendar.deleter
    def calendar(self):
        # Note that deleting the `calendar` attribute may cause the
        # `_rtime` attribute to be recalculated for the Gregorian
        # calendar, if necessary.
        if hasattr(self, '_calendar'):
            del self._calendar
        else:
            raise AttributeError("Can't delete '%s' attribute 'calendar'" %
                                 self.__class__.__name__)

        if (hasattr(self, '_rtime') and   # dch
            self._rtime.calendar != _default_calendar):
            self.units = self._units
    #--- End: def

    # ----------------------------------------------------------------
    # Property attribute: units
    # ----------------------------------------------------------------
    @property
    def units(self):
        '''

The units string. May be any string allowed by the *units* attribute
in the CF conventions.

**Examples**

>>> u = Units()
>>> u.units = 'kg'
>>> u.units
'kg'

>>> u = Units(units='percent')
>>> u.units
'percent'
>>> del u.units

'''
        try:
            return self._units
        except AttributeError:
            raise AttributeError("'%s' object has no attribute 'units'" %
                                 self.__class__.__name__)
    #--- End: def

    @units.setter
    def units(self, value):
        value = value.strip()
        if ' since ' in value:
            # --------------------------------------------------------
            # Set a reference time unit
            # --------------------------------------------------------
            value_split = value.split(' since ')
            units       = value_split[0].strip()
            ut_unit     = _ut_parse(_ut_system, _c_char_p(units), _UT_ASCII)
            # Check for bad units
            if (not ut_unit or
                not _ut_are_convertible(ut_unit, _time_ut_unit)):
                raise ValueError(
                    "Can't set unsupported unit in reference time: '%(value)s'" %
                    locals())
            #--- End: if

            # Set the calendar
            if hasattr(self, '_calendar'):
                calendar = self._calendar
                if calendar in ('standard', 'none'):
                    calendar = _default_calendar
                else:
                    pass # for now
            else:
                calendar = _default_calendar
            #--- End: if

            # Create the _utime object
            value = '%s since %s' % (units, value_split[1].strip())
            try:
                self._rtime = _utime(value, calendar=calendar)
            except ValueError:
                # Assume that the value error came from _utime()
                # complaining about the units. In this case, change
                # the units to something acceptable to _utime() and
                # afterwards overwrite the self._rtime.units attribute
                # with the correct value. If this assumption was
                # incorrect, then we'll just end up with another
                # error, this time untrapped.
                tmp_value         = 'day since '+value_split[1].strip()
                self._rtime       = _utime(tmp_value, calendar=calendar)
                self._rtime.units = units
            #--- End: try

        else:
            # --------------------------------------------------------
            # Set a unit other than a reference time unit
            # --------------------------------------------------------
            ut_unit = _ut_parse(_ut_system, _c_char_p(value), _UT_ASCII)
            if not ut_unit:
                raise ValueError("Can't set unsupported unit: '%(value)s'" %
                                 locals())
            #--- End: if

            # Delete an existing calender or reference time unit
            if hasattr(self, 'calendar'):
                del self.calendar
            if hasattr(self, '_rtime'):
                del self._rtime
        #--- End: if

        self._ut_unit = ut_unit
        self._units   = value
    #--- End: def

    @units.deleter
    def units(self):
        if hasattr(self, '_units'):
            del self._units
        else:
            raise AttributeError("%s has no attribute 'units'" %
                                 self.__class__.__name__)

        # Delete internal representations of the units
        del self._ut_unit
        if hasattr(self, '_rtime'):
            del self._rtime
    #--- End: def

    def equivalent(self, other):
        '''

Returns True if and only if numeric values in one unit are convertible
to numeric values in the other unit.

:Parameters:

    other : Units
        The other units.

:Returns:

    out : bool
        True if the units are equivalent, False otherwise.

**Examples**

>>> u = Units(units='m')
>>> v = Units(units='km')
>>> w = Units(units='s')

>>> u.equivalent(v)
True
>>> u.equivalent(w)
False

>>> u = Units(units='days since 2000-1-1')
>>> v = Units(units='days since 2000-1-1', calendar='366_day')
>>> w = Units(units='seconds since 1978-3-12')

>>> u.equivalent(v)
False
>>> u.equivalent(w)
True

'''

        if self and other:
            isreftime1 = self.isreftime
            isreftime2 = other.isreftime

            if not isreftime1 and not isreftime2:
                # --------------------------------------------------------
                # Neither unit is a reference-time unit
                # --------------------------------------------------------
                return _ut_are_convertible(self._ut_unit, other._ut_unit)

            elif isreftime1 and isreftime2:
                # --------------------------------------------------------
                # Both units are reference-time units
                # --------------------------------------------------------
                # Reference times with the same calendars are equivalent
                return self._rtime.calendar == other._rtime.calendar

        elif not self and not other:
            return True
        #--- End: if

        # Still here?
        return False
    #--- End: def

    def format(self, names=None, definition=None):
        '''

Formats the string stored in the `units` attribute in a standardized
manner. The `units` attribute is modified in place and its new value
is returned.

:Parameters:

    names : bool, optional
        Use unit names instead of symbols.

    definition : bool, optional
        The formatted string is given in terms of basic-units instead
        of stopping any expansion at the highest level possible.

:Returns:

    out : str
        The formatted string.

**Examples**

>>> u = Units(units='W')
>>> u.units
'W'
>>> u.units = u.format(names=True)
>>> u.units
'watt'
>>> u.units = u.format(definition=True)
>>> u.units
'm2.kg.s-3'
>>> u.units = u.format(names=True, definition=True)
'meter^2-kilogram-second^-3'
>>> u.units = u.format()
>>> u.units
'W'

>>> u.units='dram'
>>> u.format(names=True)
'1.848345703125e-06 meter^3'

Formatting is also available during object initialization:

>>> u = Units(units='m/s', format=True)
>>> u.units
'm.s-1'

>>> u = Units(units='dram', names=True)
>>> u.units
'1.848345703125e-06 m3'

>>> u = Units(units='W', names=True, definition=True)
>>> u.units
'meter^2-kilogram-second^-3'

'''
        if not hasattr(self, '_ut_unit'):
            raise ValueError("Can't format unit %s" % repr(self))

        opts = _UT_ASCII
        if names:
            opts |= _UT_NAMES
        if definition:
            opts |= _UT_DEFINITION

        if -1 != _ut_format(self._ut_unit,
                            _string_buffer, _sizeof_buffer,
                            opts):
            return _string_buffer.value

        raise ValueError("Can't format unit %s" % repr(self))
    #--- End: def

    def change_reftime_units(self, units):
        units_string    = self.units.split(' since ')
        units_string[0] = units
        units_string    = ' since '.join(units_string)

        if hasattr(self, 'calendar'):
            return type(self)(units=units_string, calendar=self.calendar)
        else:
            return type(self)(units=units_string)
    #--- End: def

    @staticmethod
    def conform(x, from_units, to_units, inplace=False):
        '''

Conform values in one unit to equivalent values in another, compatible
unit. Returns the conformed values.

The values may either be a numpy array or a python numeric type. The
returned value is of the same type, except that input integers are
converted to floats (see the *inplace* keyword).

:Parameters:

    x : numpy.ndarray or python numeric

    from_units : Units
        The original units of `x`

    to_units : Units
        The units to which `x` should be conformed to.

    inplace : bool, optional
        If True and `x` is a numpy array then change it in place,
        creating no temporary copies, with one exception: If `x` is of
        integer type and the conversion is not null, then it will not
        be changed inplace and the returned conformed array will be of
        float type.

:Returns:

    out : numpy.ndarray or python numeric
        The modified numeric values.

**Examples**

>>> Units.conform(2, Units('km'), Units('m'))
2000.0

>>> import numpy
>>> a = numpy.arange(5.0)
>>> Units.conform(a, Units('minute'), Units('second'))
array([   0.,   60.,  120.,  180.,  240.])
>>> a
array([ 0.,  1.,  2.,  3.,  4.])

>>> Units.conform(a,
                  Units('days since 2000-12-1'),
                  Units('days since 2001-1-1'), inplace=True)
array([-31., -30., -29., -28., -27.])
>>> a
array([-31., -30., -29., -28., -27.])


.. warning::

   Do not change the calendar of reference time units in the current
   version. Whilst this is possible, it will almost certainly result
   in an incorrect interpretation of the data or an error. Allowing
   the calendar to be changed is under development and will be
   available soon.

'''

        if not from_units.equivalent(to_units):
            raise ValueError("Units are not convertible: %s, %s" %
                             (repr(from_units), repr(to_units)))

        if from_units.equals(to_units):
            if inplace:
                return x
            else:
                return x.copy()
        #--- End: if

        ut_unit1 = from_units._ut_unit
        ut_unit2 = to_units._ut_unit

#        if from_units and to_units:
#            # Both units are defined
#            ut_unit1 = from_units._ut_unit
#            ut_unit2 = to_units._ut_unit
#        elif from_units or to_units:
#            # One unit is empty, the other not
#            raise ValueError("Units are not convertible: %s, %s" %
#                (repr(from_units), repr(to_units)))
#        else:
#            # Both units are empty: Return the original value
#            # unchanged.
#            return x

        convert = _ut_compare(ut_unit1, ut_unit2)

        isreftime1 = from_units.isreftime
        isreftime2 = to_units.isreftime

        offset = 0
        if isreftime1 and isreftime2:
            # --------------------------------------------------------
            # Both units are time-reference units
            # --------------------------------------------------------

            rtime1 = from_units._rtime
            rtime2 = to_units._rtime

#            if rtime1.calendar != rtime2.calendar:
#                raise ValueError("Units are not convertible: %s, %s" %
#                    (repr(from_units), repr(to_units)))

            # If the reference-time unit needs shifting for a new
            # origin, find the offset in units of 'from_units.units'
            jd1 = rtime1._jd0
            jd2 = rtime2._jd0
            if jd1 != jd2:
                offset = jd2 - jd1  # Non-zero offset in units of 'days'
#                if convert:
#                    cv_converter = _ut_get_converter(_time_ut_unit, ut_unit1)
#                    scale        = _c_double(1.0)
#                    pointer      = ctypes.pointer(scale)
#                    # Modify scale in place
#                    _cv_convert_doubles(cv_converter,
#                                        pointer,
#                                        _c_size_t(1),
#                                        pointer)
# Offset in units of 'from_units.units'
#                    offset *= scale.value  
#                    _cv_free(cv_converter)
#            #--- End: if

#        elif isreftime1 or isreftime2:
#            # One unit is a time-reference unit, the other is not
#            raise ValueError("Units are not convertible: %s, %s" %
#                (repr(from_units), repr(to_units)))
        #--- End: if

        # ----------------------------------------------------------------
        # If the two units are identical then no need to alter the
        # value, so return it unchanged.
        # ----------------------------------------------------------------
#        if not convert and not offset:
#            return x

        if convert:
            cv_converter = _ut_get_converter(ut_unit1, ut_unit2)
            if not cv_converter:
                _cv_free(cv_converter)
                raise ValueError("Units are not convertible: %s, %s" %
                                 (repr(from_units), repr(to_units)))
        #-- End: if

        # ----------------------------------------------------------------
        # Find out if x is an numpy array or a python number
        # ----------------------------------------------------------------
        if isinstance(x, (float, int, long)):
            x_is_numpy = False
        else:
            x_is_numpy = True

            if not x.flags.contiguous:
                x = numpy.array(x, order='C')
#ARRRGGHH dch

            # ----------------------------------------------------------------
            # Convert an integer numpy array to a float numpy array
            # ----------------------------------------------------------------
            if inplace and x.dtype.kind is 'i':
                if x.dtype.char is 'i':
                    y      = x.view(dtype='float32')
                    y[...] = x
                    x.dtype = numpy.dtype('float32')
                elif x.dtype.char is 'l':
                    y      = x.view(dtype='float64')
                    y[...] = x
                    x.dtype = numpy.dtype('float64')

            elif not inplace:
                if x.dtype.kind is 'i':
                    if x.dtype.char is 'i':
                        x = numpy.array(x, dtype='float32')
                    elif x.dtype.char is 'l':
                        x = numpy.array(x, dtype='float64')
                else:
                    x = x.copy()
        #--- End: if

        # ------------------------------------------------------------
        # Convert the array to the new units
        # ------------------------------------------------------------
        if convert:

            if x_is_numpy:
                # Create a pointer to the array cast to the appropriate
                # ctypes object
                itemsize = x.dtype.itemsize
                pointer  = x.ctypes.data_as(_ctypes_POINTER[itemsize])

                # Convert the array in place
                _cv_convert_array[itemsize](cv_converter,
                                            pointer,
                                            _c_size_t(x.size),
                                            pointer)
            else:
                # Create a pointer to the number cast to a ctypes double
                # object.
                y  = _c_double(x)
                pointer = ctypes.pointer(y)
                # Convert the pointer
                _cv_convert_doubles(cv_converter,
                                    pointer,
                                    _c_size_t(1),
                                    pointer)
                # Reset the number
                x = y.value
            #--- End: if

            _cv_free(cv_converter)
        #--- End: if

        # ------------------------------------------------------------
        # Apply an offset for reference-time units
        # ------------------------------------------------------------
        if offset:
            # Convert the offset from 'days' to the correct units and
            # subtract it from x
            if _ut_compare(_time_ut_unit, ut_unit2):

                cv_converter = _ut_get_converter(_time_ut_unit, ut_unit2)
                scale   = numpy.array(1.0, dtype='float64')
                pointer = scale.ctypes.data_as(ctypes.POINTER(ctypes.c_double))
                _cv_convert_doubles(cv_converter,
                                    pointer,
                                    _c_size_t(scale.size),
                                    pointer)
                _cv_free(cv_converter)

                offset *= scale.item()
            #--- End: if

            x -= offset
        #--- End: if

        return x
    #--- End: def

    def copy(self):
        '''

Return a deep copy.

Equivalent to ``copy.deepcopy(u)``.

:Returns:

    out :
        The deep copy.

**Examples**

>>> v = u.copy()

'''
        if not self:
            return type(self)()

        new = type(self)()
        
        new._ut_unit = self._ut_unit
        new.units    = self.units
        if hasattr(self, '_calendar'):
            new._rtime = self._rtime
            new._calendar = self._calendar
            
        return new

#        return type(self)(units    = self.units,
#                          calendar = getattr(self, 'calendar', None))
    #--- End: def

    def dump(self, id=None, omit=()):
        '''

'''
        if id is None:
            id = self.__class__.__name__

        string = []

        for attr in self.__slots__:
            try:
                string.append("%s.%s = '%s'" % (id, attr, getattr(self, attr)))
            except AttributeError:
                pass
        #--- End: for

        return '\n'.join(string)
    #--- End: def

    def equals(self, other, rtol=None, atol=None):
        '''

Return True if and only if numeric values in one unit are convertible
to numeric values in the other unit and their conversion is a scale
factor of 1.

:Parameters:

    other : Units
        The other units.

:Returns:

    out : bool
        True if the units are equal, False otherwise.

**Examples**

>>> u = Units(units='km')
>>> v = Units(units='1000m')
>>> u.equals(v)
True

>>> u = Units(units='m s-1')
>>> m = Units(units='m')
>>> s = Units(units='s')
>>> u.equals(m)
False
>>> u.equals(m/s)
True
>>> (m/s).equals(u)
True

Undefined units are considered equal:

>>> u = Units()
>>> v = Units()
>>> u.equals(v)
True

'''
        isreftime1 = self.isreftime
        isreftime2 = other.isreftime

        if self and other:
            try:
                if _ut_compare(self._ut_unit, other._ut_unit):
                    return False
            except AttributeError:
                return False

            if isreftime1 and isreftime2:
                # Both units are reference-time units, so compare
                # their origin, calendar and time zone offset
                rtime1 = self._rtime
                rtime2 = other._rtime

                return (rtime1._jd0     == rtime2._jd0     and
                        rtime1.calendar == rtime2.calendar and
                        rtime1.tzoffset == rtime2.tzoffset)
            elif isreftime1 or isreftime2:
                # One unit is a reference-time and the other is not,
                # so they're not equal
                return False
            else:
                # Both units are non-reference-time units and are
                # equal
                return True

        elif self or other:
            return False
        #--- End: if

        # Still here? Then both units are undefined and therefore
        # equal
        return True
    #--- End: def

    def log(self, base):
        '''

Returns the logarithmic unit corresponding to the given logarithmic
base.

:Parameters:

    base : int or float
        The logarithmic base.

:Returns:

    out : Units
        The logarithmic unit corresponding to the given logarithmic
        base.

**Examples**

>>> u = Units(units='W', names=True)
>>> u
<CF Units: watt>

>>> u.log(10)
<CF Units: lg(re 1 W)>
>>> u.log(2)
<CF Units: lb(re 1 W)>

>>> import math
>>> u.log(math.e)
<CF Units: ln(re 1 W)>

>>> u.log(3.5)
<CF Units: 0.798235600147928 ln(re 1 W)>

'''
        try:
            ut_unit = _ut_log(_c_double(base), self._ut_unit)
        except TypeError:
            pass
        else:
            if ut_unit:
                return type(self)(_ut_unit=ut_unit)
        #--- End: try

        raise ValueError("Can't take the logarithm to the base %s of %s" %
                         (repr(base), repr(self)))
    #--- End def

#--- End: class
